package dao;

import entity.Man;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ManDao extends BaseDao {
    Connection conn=null;//1.链接数据库
    PreparedStatement pst=null;//2.数据周转
    ResultSet rs=null;//3.结果集

    public List<Man> getAll() throws SQLException {
        String sql="SELECT * FROM man";

        conn=getConnection();//1.1链接数据库
        pst=conn.prepareStatement(sql);//2.2数据周转
        rs=pst.executeQuery();//3.3.数据周转
        List<Man> Mans=new ArrayList<>();
        while (rs.next()){
            Man man=new Man(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getInt("age"),
                    rs.getString("diZhi"),
                    rs.getString("major")
            );
            Mans.add(man);
        }
        close(rs,pst,conn);
        return Mans;
    }
    public void addMan(Man man){
        String sql="INSERT INTO man (name,age,diZhi,major) VALUES(?,?,?,?)";
        try {
            conn=getConnection();
            pst=conn.prepareStatement(sql);
            pst.setString(1,man.getName());
            pst.setInt(2,man.getAge());
            pst.setString(3,man.getDiZhi());
            pst.setString(4,man.getMajor());
            pst.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(null,pst,conn);
        }
    }
    public void UpdateMan(Man man){
        String sql="UPDATE man SET `name`=?,age=?,diZhi=?,major=? WHERE id=?";
        try {
            conn=getConnection();
            pst=conn.prepareStatement(sql);
            pst.setString(1,man.getName());
            pst.setInt(2,man.getAge());
            pst.setString(3,man.getDiZhi());
            pst.setString(4,man.getMajor());
            pst.setInt(5, man.getId()); // 设置ID参数
            pst.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(null,pst,conn);
        }
    }

    public void DeleteMan(int id) throws SQLException{
        String sql="DELETE FROM student where id=?";
        conn=getConnection();
        pst=conn.prepareStatement(sql);
        pst.setInt(1,id);
        pst.execute();
        close(null,pst,conn);
    }
}
